


const wxLogin = () => {
    return checkSession().catch(err => {
        return login();
    });
}

// const wxGetSe


const checkSession = () => {
    return new Promise((res, rej) => {
        wx.checkSession({
            success: (result) => {
                console.log("have session is login")
                const loginInfo = { isLogin: true };
                res(loginInfo);
            },
            fail: () => {
                console.log("no session should login")
                rej();
            },
            complete: () => { }
        });

    });
}

const login = () => {
    return new Promise((res, rej) => {
        wx.login({
            timeout: 10000,
            success: (result) => {
                console.log('获取的login code ' + result.code)
                if (!result.code) {
                    wx.showToast({
                        title: '登录失败',
                        icon: 'none',
                        image: '',
                        duration: 1500,
                        mask: false,
                        success: (result) => {

                        },
                        fail: () => { },
                        complete: () => { }
                    });

                    return
                }
                const app = getApp();
                const mpAppInfo = app.mpAppInfo;
                mpAppInfo.setCode(result.code);
                res(result);
            },
            fail: () => {
                rej();
            },
            complete: () => { }
        });

    });
}

const getSetting = () => {
    return new Promise((res, rej) => {
        wx.getSetting({
            success: result => {
                res(result);
            },
            fail: () => {
                rej();
            }
        })
    });
}

const getUserInfo = (withCredentials = true) => {
    return new Promise((res, rej) => {
        wx.getUserInfo({
            withCredentials: withCredentials,//是否带上登录态信息。当 withCredentials 为 true 时，要求此前有调用过 wx.login 且登录态尚未过期，此时返回的数据会包含 encryptedData, iv 等敏感信息；当 withCredentials 为 false 时，不要求有登录态，返回的数据不包含 encryptedData, iv 等敏感信息。
            lang: 'zh_CN',
            timeout: 10000,
            success: (result) => {
                res(result);
            },
            fail: () => {
                wx.showToast({
                    title: '微信授权登录失败',
                    icon: 'none',
                    image: '',
                    duration: 1500,
                    mask: false,
                    success: (result) => {

                    },
                    fail: () => { },
                    complete: () => { }
                });

                rej();
            },
            complete: () => { }
        });

    });
}

export default {
    wxLogin,
    checkSession,
    login,
    getSetting,
    getUserInfo
}